import { Request, Response } from 'express';
import { intersection } from 'lodash';
// import roles from './database/roles.json';
import * as fs from 'fs';
import { isEmpty } from './utils';
import dayjs from 'dayjs';

export default {
  // 支持值为 Object 和 Array
  'GET /api/roleList': async (req: Request, res: Response) => {
    console.log('请求参数', req.query);
    const { current, pageSize, roleName } = req.query as unknown as ROLE.RoleParams;
    const roleListStr = fs.readFileSync('./mock/database/roles.json', 'utf-8');
    if (!roleListStr) {
      res.send({
        success: true,
        data: {
          list: [],
          hasNextPage: false,
          current,
          pageSize,
        },
      });
      return;
    }

    let resRoles: ROLE.RoleType[] = [];
    const roleList: ROLE.RoleType[] = JSON.parse(roleListStr);
    let total = roleList.length;
    if (!isEmpty(roleList)) {
      if (roleName) {
        const tempList = roleList.filter((role) => {
          return intersection([...role.name], [...roleName]).length > 0;
        });
        total = tempList.length;
        resRoles = tempList.slice((current - 1) * pageSize, current * pageSize);
      } else {
        resRoles = roleList.slice((current - 1) * pageSize, current * pageSize);
      }
      res.send({
        success: true,
        data: {
          list: resRoles,
          hasNextPage: total > current * pageSize,
          current,
          pageSize,
          total,
        },
      });
    } else {
      res.send({
        success: true,
        data: {
          list: [],
          hasNextPage: false,
          current,
          pageSize,
          total: 0,
        },
      });
    }

    // console.log('角色', roles);

    // res.send({
    //   success: true,
    //   data: {
    //     list: roles,
    //     hasNextPage: true,
    //     current: 1,
    //     pageSize: 10,
    //   },
    // });
  },
  'POST /api/role': async (req: Request, res: Response) => {
    const { roleName } = req.body as unknown as { roleName: string };
    if (!roleName) {
      res.send({
        data: null,
        errorMessage: '请填写角色名称！',
        success: false,
      });
      return;
    }

    // if (!operator) {
    //   res.send({
    //     data: null,
    //     errorMessage: '请填写操作人名称！',
    //     success: false,
    //   });
    //   return;
    // }

    const roleListStr = fs.readFileSync('./mock/database/roles.json', 'utf-8');
    const roleList: ROLE.RoleType[] = roleListStr ? JSON.parse(roleListStr) : [];
    const now = dayjs();
    roleList.push({
      name: roleName,
      createTime: now.format('YYYY-MM-DD HH:mm:ss'),
      authTime: '',
      authName: '',
      operator: '',
      id: `JS${now.valueOf()}`,
    });
    fs.writeFileSync('./mock/database/roles.json', JSON.stringify(roleList));
    res.send({
      success: true,
      data: [],
    });
  },
  'PUT /api/role': async (req: Request, res: Response) => {
    const { roleName, id } = req.body as unknown as { roleName: string; id: string };
    if (!roleName) {
      res.send({
        data: null,
        errorMessage: '请填写角色名称！',
        success: false,
      });
      return;
    }

    if (!id) {
      res.send({
        data: null,
        errorMessage: '角色id不能为空 ！',
        success: false,
      });
      return;
    }

    const roleListStr = fs.readFileSync('./mock/database/roles.json', 'utf-8');
    const roleList: ROLE.RoleType[] = roleListStr ? JSON.parse(roleListStr) : [];
    const editRole = roleList.find((item) => item.id === id);
    if (editRole) {
      Object.assign(editRole, { name: roleName });
      fs.writeFileSync('./mock/database/roles.json', JSON.stringify(roleList));
      res.send({
        success: true,
        data: [],
      });
    } else {
      res.send({
        data: null,
        errorMessage: '没有找到待编辑角色！',
        success: false,
      });
    }
  },
  'DELETE /api/role': async (req: Request, res: Response) => {
    console.log('请求参数 mock/role >> delete', req.query);
    const { id } = req.query as unknown as Pick<ROLE.RoleType, 'id'>;
    const roleListStr = fs.readFileSync('./mock/database/roles.json', 'utf-8');
    if (!roleListStr) {
      res.send({
        data: null,
        errorMessage: '暂无角色可删',
        success: false,
      });
      return;
    }

    const roleList: ROLE.RoleType[] = JSON.parse(roleListStr);
    const delIndex = roleList.findIndex((item) => item.id === id);
    if (delIndex > -1) {
      roleList.splice(delIndex, 1);
      fs.writeFileSync('./mock/database/roles.json', JSON.stringify(roleList));
      res.send({
        success: true,
        data: [],
      });
    } else {
      res.send({
        data: null,
        errorMessage: '没有该角色！',
        success: false,
      });
    }
  },
  'GET /api/allRoleList': async (req: Request, res: Response) => {
    const roleListStr = fs.readFileSync('./mock/database/roles.json', 'utf-8');
    res.send({
      success: true,
      data: roleListStr ? JSON.parse(roleListStr) : [],
    });
  },
  'GET /api/authRole': async (req: Request, res: Response) => {
    const { id } = req.query as unknown as ROLE.RoleAuthInfoParams;
    if (!id) {
      res.send({
        data: null,
        errorMessage: '角色id不能为空！',
        success: false,
      });
      return;
    }

    const authMenuRecordStr = fs.readFileSync('./mock/database/authMenuRecord.json', 'utf-8');
    const authMenuRecord: Record<string, string[]> = authMenuRecordStr
      ? JSON.parse(authMenuRecordStr)
      : {};
    res.send({
      success: true,
      data: authMenuRecord[id] || [],
    });
  },
  'POST /api/authRole': async (req: Request, res: Response) => {
    const { menuIdArr, id } = req.body as unknown as ROLE.AuthRoleParams;
    if (!id) {
      res.send({
        data: null,
        errorMessage: '角色id不能为空！',
        success: false,
      });
      return;
    }

    if (isEmpty(menuIdArr)) {
      res.send({
        data: null,
        errorMessage: '授权菜单id不能为空',
        success: false,
      });
      return;
    }

    const authMenuRecordStr = fs.readFileSync('./mock/database/authMenuRecord.json', 'utf-8');
    const authMenuRecord: Record<string, string[]> = authMenuRecordStr
      ? JSON.parse(authMenuRecordStr)
      : {};

    const roleListStr = fs.readFileSync('./mock/database/roles.json', 'utf-8');
    const roleList: ROLE.RoleType[] = roleListStr ? JSON.parse(roleListStr) : [];
    const authRole = roleList.find((item) => item.id === id);
    const currentRecordStr = fs.readFileSync('./mock/database/currentRecord.json', 'utf-8');
    const currentRecord = currentRecordStr ? JSON.parse(currentRecordStr) : {};
    if (authRole) {
      Object.assign(authRole, {
        authTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        authName: currentRecord?.currentUser.userName || '',
      });
      fs.writeFileSync('./mock/database/roles.json', JSON.stringify(roleList));
    }
    authMenuRecord[id] = menuIdArr;
    fs.writeFileSync('./mock/database/authMenuRecord.json', JSON.stringify(authMenuRecord));

    res.send({
      success: true,
      data: null,
    });
  },
};
